#!/bin/bash
#
# USAGE:
#	archive create [path/to/folder] [archiveName]
#
# DESCRIPTION:
#  archive is an ADORE function. 
#  It creates a tar archive for the given folder, as well as creating
#  checksums (md5sum) for each file. The md5sums are verified during
#  extraction. 
#
# INPUT:
#  path/to/folder: Relative (or full) path to the folder to be archived. 
#    If omitted current folder "." is used.
#  archiveName: Optional input for output archive file name. If omitted
#    the name of the parent folder is used (last part of the path to folder.)
#
# OUTPUT:
#  folderName.tar

# create archive
function archive_create(){
 local inputPath=`echo ${1:-.}`
 local folderPath=`canonicalPath ${1:-.}` 
 local folderName=`echo ${folderPath##*/}`
 local archiveName="${2}"
 if [ ${folderName} == "." ]; then #if folder path is not specified use current folder
   folderPath=`echo ${folderPath%/.}`
   folderName=`echo ${folderPath##*/}`
 fi
 if [ "${archiveName:-isEmpty}" == "isEmpty" ]; then #if archivename is not specified use parent folder
   archiveName=${folderName};
 fi
 rm -rf /tmp/archive.md5
 echo ${folderPath} >> /tmp/archive.md5
 tar -cvf ${archiveName}.tar ${inputPath} | xargs -I '{}' sh -c "test -f '{}' && md5sum '{}'" | tee -a /tmp/archive.md5
 mv /tmp/archive.md5 archive.md5
 tar -rf ${archiveName}.tar archive.md5
 rm -rf archive.md5
}

# extract archive
function archive_extract(){
 local outFolderPath=`canonicalPath ${1}`
 outFolderPath=`dirname ${outFolderPath}`
# local archiveName=`basename ${1}`
# archiveName=`echo ${archiveName%.*}`
 #mkdir -p ${archiveName}
 tar -xvf ${1} #-C ${archiveName}
 local md5file=archive.md5
 local inFolderPath=`head -n1 ${md5file}`
 sed -i 1d ${md5file}  
 sed -i "s@ \./@ ${outFolderPath}/@g" ${md5file}
 md5sum -c ${md5file}
 mvDorisFiles -s ${inFolderPath} ${outFolderPath}
}
#Main
case ${1} in
  create)
    shift 
    archive_create ${@}
  ;;
  extract)
    shift
    archive_extract ${@}
  ;;
  *)
    h archive
  ;;
esac
  